package com.hc.usb.impl;

import android.content.Context;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class USBHelper {
    private static USBHelper mInstance;
    private Context mContext;
    private USBHelper(Context context) {
        mContext = context;
    }

    public static USBHelper getInstance(Context context) {
        if(mInstance == null){
            synchronized (USBHelper.class){
                if(mInstance == null){
                    mInstance = new USBHelper(context.getApplicationContext());
                }
            }
        }
        return mInstance;
    }

    public void findDevices(UsbManager usbManager, List<UsbDevice> usbDevices){
        HashMap<String, UsbDevice> deviceHashMap = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceHashMap.values().iterator();
        while (deviceIterator.hasNext()){
            usbDevices.add(deviceIterator.next());
        }
    }

    public USBConnection createConnection(UsbDevice usbDevice){
        for (int i = 0; i < usbDevice.getInterfaceCount(); i++) {
            UsbInterface usbInterface = usbDevice.getInterface(i);
            if(usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_MASS_STORAGE
                    && usbInterface.getInterfaceSubclass() == 0x06
                    && usbInterface.getInterfaceProtocol() == 0x50){
                UsbEndpoint readPoint = null,writePoint = null;
                for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
                    UsbEndpoint endpoint = usbInterface.getEndpoint(j);
                    if(endpoint.getDirection() == UsbConstants.USB_DIR_OUT){
                        writePoint = endpoint;
                    }else {
                        readPoint = endpoint;
                    }
                }
                return new USBConnection(usbDevice,usbInterface,readPoint,writePoint);
            }
        }
        return null;
    }
}
